<template>
  <div class="room">
    <div class="flex-1 content_warp">
      <div class="message_container_warp">
        <div class="sheader user-select flex-center" data-type="top">
          <div v-show="finish && list.length" class="f14 c-9">
            没有更多消息了
          </div>
          <div v-show="loading" class="c-9 f14">
            <i class="el-icon-loading"></i> 正在加载数据中 ...
          </div>
        </div>

        <div
          v-for="item in list"
          :key="item.id"
          :class="['mt20', 'message_' + item.id]"
        >
          <div
            :class="{
              messageRoom_item: true,
              messageRoom_right: item.sender_type == 'doctor',
            }"
          >
            <img class="messageRoom_item_image" :src="getImage(item)" alt="" />
            <div v-if="item.type === 'txt'" class="messageRoom_item_message">
              {{ item.content }}
            </div>
            <imgWarp
              v-else-if="item.type === 'img'"
              :ref="item.class"
              :item="item"
              data-type="img"
            ></imgWarp>

            <div v-else-if="item.type == 'patientCard'">
              <div
                @click="preViewData(item)"
                style="
                  width: 350px;
                  height: 130px;
                  border-radius: 15px;
                  border: 1px solid #eee;
                  background-color: white;
                  cursor: pointer;
                "
              >
                <div
                  style="
                    padding: 15px;
                    margin: 10px;
                    display: flex;
                    align-items: center;
                    font-size: 16px;
                    border-bottom: 1px solid #ccc;
                  "
                >
                  {{ JSON.parse(item.content).patient_name }}
                  {{ JSON.parse(item.content).patient_gender }}
                  {{ JSON.parse(item.content).age }}
                  <!--    <van-icon name="arrow" /> -->
                </div>
                <div class="ml15">
                  <div>
                    部门名称：{{ JSON.parse(item.content).department_name }}
                  </div>
                  <div>
                    病情描述：{{ JSON.parse(item.content).patient_status }}
                  </div>
                </div>
              </div>
            </div>

            <div v-else>
              <div
                @click="preView(item)"
                style="
                  width: 350px;
                  height: 130px;
                  border-radius: 15px;
                  border: 1px solid #eee;
                  background-color: white;
                  cursor: pointer;
                "
              >
                <div
                  style="
                    background-color: #66bfa4;
                    padding: 15px;
                    margin: 10px;
                    display: flex;
                    align-items: center;
                    font-size: 16px;
                  "
                >
                  处方单
                  <!--    <van-icon name="arrow" /> -->
                </div>
                <div class="ml15">
                  <div>诊断：{{ JSON.parse(item.content).diagnosis }}</div>
                  <div class="flex">
                    <div>RP：</div>
                    <span
                      v-for="i in JSON.parse(item.content).prescription"
                      :key="i.id"
                    >
                      <span style="margin-right: 10rpx">{{ i.name }} </span>
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div
          class="footer user-select"
          data-type="bottom"
          style="color: transparent"
        >
          -----
        </div>
      </div>
    </div>
    <div class="tools flex-space-between">
      <form style="display: none">
        <input
          type="file"
          ref="fileImageRef"
          accept="image/*"
          @change="upload"
        />
        <input
          type="file"
          ref="uploadFileRef"
          accept=".zip,.rar,.pdf,.docx,.doc,.xlsx,.csv,.txt"
          @change="upload"
        />
      </form>
      <div class="flex">
        <div @click="chooseImage" class="showPointer mr20">
          <svgIcon iconClass="uploadImg" size="35" />
          <div>上传图片</div>
        </div>
        <div @click="refundClick" class="showPointer mr20">
          <svgIcon iconClass="tuikuan" size="35" />
          <div>退款</div>
        </div>
        <div @click="prescribingClick" class="showPointer mr20">
          <svgIcon iconClass="kaichufang" size="35" />
          <div>开处方</div>
        </div>
        <!--  <div @click="reviewPrescribingClick" class="showPointer mr20">
          <svgIcon iconClass="kaichufang" size="35" />
          <div>撤回处方</div>
        </div> -->
        <!--    <div @click="chooseImage" class="showPointer mr20">
          <svgIcon iconClass="uploadImg" size="30" />
          <div>视频</div>
        </div> -->
        <div @click="medicalRecords" class="showPointer mr20">
          <svgIcon iconClass="bingli" size="35" />
          <div>写病历</div>
        </div>
        <div @click="referral" class="showPointer mr20">
          <svgIcon iconClass="zhuanzhen" size="35" />
          <div>转号</div>
        </div>
        <div
          @click="reportClick"
          v-if="row.order_type == '团队问诊'"
          class="showPointer mr20"
        >
          <svgIcon iconClass="药品" size="35" />
          <div>上传会诊报告</div>
        </div>

        <!--   <div @click="referral" class="showPointer mr20">
          <svgIcon iconClass="药品" size="35" />
          <div>开药</div>
        </div> -->
        <!-- <div @click="referral" class="showPointer mr20">
          <i class="el-icon-video-camera"></i>
          <div>视频聊天</div>
        </div> -->
      </div>
    </div>
    <div v-if="row.cancel_time">
      <div class="flex-center mb15 mt15">
        <div class="fb" style="color:gray text-align: center; font-size: 26px">
          问诊已结束
        </div>
      </div>
    </div>
    <div v-else-if="row.finish_time">
      <div class="flex-center mb15 mt15">
        <div class="fb" style="font-size: 25px; color: gray">问诊已结束</div>
      </div>
    </div>

    <div v-else class="entry_box">
      <!--         
        v-drag="dragPasteImage"
        v-paste="pasteImage" -->
      <div
        ref="editor_content"
        class="editor_content"
        spellcheck="true"
        contenteditable
        @keydown="onKeydownEvent($event)"
        @input="onInput($event)"
        placeholder="请输入..."
      ></div>
      <div class="entry_box_btn flex-align-center">
        <div class="f12 c-9 mr10">Enter发送 / Shift+Enter换行</div>
        <el-button
          size="small"
          :disabled="isDisabled"
          type="primary"
          @click="onClickSend"
          >发 送</el-button
        >
      </div>
    </div>
    <prescribing ref="prescribing" :id="row.id" :preData="row" />
    <medicalRecords ref="medicalRecords" :id="row.id" />
    <referral ref="referral" :id="row.id" @dialogClose="dialogClose" />
    <importData ref="importData" />
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import {
  ApiGetOrderMessageRecord,
  ApiRefund,
  ApiAdviceRollback,
  ApiPostTeamReport,
  ApiAdminAdviceList,
} from "@/api";
import { debounce } from "@/util";
import imgWarp from "./imgWarp.vue";
import prescribing from "./prescribing.vue";
import medicalRecords from "./medicalRecords.vue";
import referral from "./referral.vue";
import doctorImg from "@/assets/image/jsDoctor.jpg";
import userImg from "@/assets/image/jsDoctor.jpg";
import bus from "@/bus";
import importData from "./importData.vue";

const imgMap = new Map();

export default {
  components: {
    imgWarp,
    prescribing,
    medicalRecords,
    referral,
    importData,
  },

  props: ["row", "dialogVisible"],

  computed: {
    ...mapState(["userState"]),
  },

  inject: ["WS"],

  watch: {
    row: {
      deep: true,
      immediate: true,
      handler(val, oldVal) {
        if (val) {
          console.log(val);
          bus.$off("newMessage");
          this.list = [];
          this.row = val;
          this.uid = this.row.patient_id;
          this.finish = false;
          this.WS.send({
            action: "openPage",
            consultation_order_id: this.row.id,
          });
          bus.$on("newMessage", this.onNewMessage.bind(this));
          this.$nextTick((_) => {
            this.message_container_warp = document.querySelector(
              ".message_container_warp"
            );
            const header =
              this.message_container_warp.querySelector(".sheader");
            const footer = this.message_container_warp.querySelector(".footer");
            /*     this.getMessageContent() */
            this.IO = new IntersectionObserver(
              (changes) => {
                changes.forEach((element) => {
                  const type = element.target.dataset.type;
                  if (element.isIntersecting) {
                    if (type === "top") this.getMessageContent();
                    if (type === "bottom") this.isFooter = true;

                    // 图片懒加载
                    if (type === "img") {
                      this.IO.unobserve(element.target);
                      const setImgUrl = imgMap.get(element.target);
                      setImgUrl();
                      imgMap.delete(element.target);
                    }
                  } else {
                    if (type === "bottom") this.isFooter = false;
                  }
                });
              },
              {
                root: this.message_container_warp,
                threshold: [0, 1],
              }
            );
            this.IO.observe(header);
            this.IO.observe(footer);
          });

          /*      this.clearMessageCount(this.uid); */
        }
      },
    },
    /*     dialogVisible: {
          deep: true,
          immediate: true,
          handler(val) {
            if (!val) {
              this.IO && this.IO.disconnect();
              this.WS.send({ action: "openPage", uid: '我要关闭了' });
              bus.$off("newMessage");
              window.stop();
            }
          }
        }, */

    isShowChat(val) {
      if (val && this.markFlag) {
        this.clearMessageCount(this.uid);
        this.markFlag = false;
        this.$nextTick((_) => {
          this.scrollToSeat(true);
        });
      }
    },
  },

  data() {
    return {
      isDisabled: true,
      content: "",
      list: [],
      finish: false,
      loading: false,
      isFooter: false,
      markFlag: false, // 标记隐藏后是否有消息
      number: 1,
    };
  },

  /* mounted() {
    this.uid = this.openRoom.patient_id;
    this.WS.send({ action: "openPage", uid: this.uid });
    bus.$on("newMessage", this.onNewMessage.bind(this));

    this.message_container_warp = document.querySelector(
      ".message_container_warp"
    );
    const header = this.message_container_warp.querySelector(".sheader");
    const footer = this.message_container_warp.querySelector(".footer");

    this.IO = new IntersectionObserver(
      (changes) => {
        changes.forEach((element) => {
          const type = element.target.dataset.type;
          if (element.isIntersecting) {
            if (type === "top") this.getMessageContent();
            if (type === "bottom") this.isFooter = true;

            // 图片懒加载
            if (type === "img") {
              this.IO.unobserve(element.target);
              const setImgUrl = imgMap.get(element.target);
              setImgUrl();
              imgMap.delete(element.target);
            }
          } else {
            if (type === "bottom") this.isFooter = false;
          }
        });
      },
      {
        root: this.message_container_warp,
        threshold: [0, 1],
      }
    );

    this.IO.observe(header);
    this.IO.observe(footer);

    this.clearMessageCount(this.uid);
  }, */

  destroyed() {
    this.IO && this.IO.disconnect();
    this.WS.send({ action: "openPage", consultation_order_id: this.row.id });
    bus.$off("newMessage");
    window.stop();
  },

  methods: {
    preViewData(e){
      console.log(e)
    },
    preView(e) {
      let id = JSON.parse(e.content).preMessageId;
      ApiAdminAdviceList({ advice_id: id }).then((res) => {
        if (res.code == 200) {
          window.open(res.data[0].advice_pic);
        }
      });
    },
    /*  , "clearMessageCount" */
    /*   ...mapMutations(["changeMessageList"]),
     */
    //上传图片
    chooseImage() {
      this.$refs.fileImageRef.click();
    },
    //转诊
    referral() {
      this.$refs.referral.show();
    },

    //病历
    medicalRecords() {
      this.$refs.medicalRecords.show(this.row.patient_gender);
    },

    reviewPrescribingClick() {
      ApiAdviceRollback(this.row.id).then((res) => {
        if (res.code == 200) {
          this.$message({
            type: "success",
            message: "撤回成功!",
          });
        }
      });
    },

    dialogClose() {
      this.$emit("dialogClose", false);
    },

    //会诊报告
    reportClick() {
      this.$refs.importData.show(this.row.id);
      /*   this.$prompt("填写会诊报告", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(({ value }) => { */
      //退款原因的方法
      /*      ApiPostTeamReport({ order_id: this.row.id, content: value }).then(
          (res) => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: "添加成功!",
              });
              this.dialogClose();
            }
          }
        );
      }); */
    },
    //,退款
    refundClick() {
      /*   console.log('11112222') */
      //先进行输入原因
      /*  ApiRefund() */
      this.$prompt("请输入退款原因", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(({ value }) => {
        //退款原因的方法
        ApiRefund({ order_id: this.row.id, reason: value }).then((res) => {
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "退款成功!",
            });
            this.dialogClose();
          }
        });
      });
    },

    //开处方
    prescribingClick() {
      this.$refs.prescribing.show();
    },

    upload(e) {
      const file = e.target.files[0];
      if (!file) return;
      e.target.value = "";
      if (/.+\.(webp)$/.test(file.name)) {
        this.$message.error("暂不支持该格式图片");
        return;
      }
      const time = new Date();
      const parmas = {
        consultation_order_id: this.row.id,
        action: "message",
        receiver: this.row.uid,
        content: "",
        type: "img",
        sender: this.row.doctor_id,
        sender_type: "doctor",
        id: time.getTime(),
        file: file,
      };
      /*  this.changeMessageList({
         patient_id: this.row.patient_id,
         patient_name: this.row.patient_name,
         count: 0,
         message: "[图片]",
         time: time,
       }); */
      this.list.push(parmas);
      this.$nextTick((_) => {
        this.scrollToSeat(true);
      });
    },

    onNewMessage(data) {
      if (data.consultation_order_id == this.row.id) {
        const refClass = "imgWarp_" + this.number;
        if (data.type === "img") {
          data.class = refClass;
        }
        this.list.push(data);
        if (!this.isShowChat) this.markFlag = true;

        this.$nextTick(() => {
          if (this.isFooter) this.scrollToSeat(true);
          if (data.type === "img" && this.$refs[refClass]) {
            this.$refs[refClass].forEach((item) => {
              imgMap.set(item.$el, item.setImgUrl);
              this.IO.observe(item.$el);
            });
            this.number++;
          }
        });
      }
    },

    getImage(item) {
      if (item.sender_icon) {
        if (item.sender_icon.indexOf("http") == 0) {
          return item.sender_icon;
        } else {
          return this.$path + item.sender_icon;
        }
      } else {
        return this.$path + this.userState.icon;
      }
    },

    onClickSend() {
      this.sendMessage(this.$refs.editor_content.innerText.trim());
    },

    sendMessage(text) {
      if (text.length === 0) {
        return;
      }
      if (text.length > 1024) {
        this.$message.warning("发送内容超长，请分条发送！");
        return;
      }

      const time = new Date();

      const parmas = {
        consultation_order_id: this.row.id,
        action: "message",
        receiver: this.row.uid,
        content: text,
        type: "txt",
        sender: this.row.doctor_id,
        sender_type: "doctor",
        id: time.getTime(),
      };

      this.WS.send(parmas, (ops) => {
        this.list.push(parmas);
        this.$refs.editor_content.innerText = "";
        this.isDisabled = true;
        /*   this.changeMessageList({
            patient_id: this.row.patient_id,
            patient_name: this.row.patient_name,
            count: 0,
            message: text,
            time: time,
          }); */
        this.$nextTick((_) => {
          this.scrollToSeat(true);
        });
      });
    },

    onKeydownEvent(e) {
      // if (e.keyCode == 38 || e.keyCode == 40) {
      //   e.preventDefault()
      // }

      let text = e.target.innerText.trim();

      // 空信息禁止换行
      if (e.keyCode == 13 && !text) {
        return e.preventDefault();
      }

      // 回车发送消息
      if (e.keyCode == 13 && e.shiftKey == false && text) {
        this.sendMessage(text);
        return e.preventDefault();
      }
    },

    onInput: debounce(
      function (e) {
        this.isDisabled = !e.target.innerText.trim();
      },
      200,
      false
    ),

    getMessageContent() {
      if (this.finish || this.loading) return;
      const scrollHeight = this.message_container_warp.scrollHeight;
      this.loading = true;
      const ops = {
        size: 20,
        order_id: this.row.id,
        message_id: this.list[0]?.id ?? "",
      };
      ApiGetOrderMessageRecord(ops)
        .then((res) => {
          const data = res.data || [];
          const refClass = "imgWarp_" + this.number;
          let imgFlag = false;
          data.forEach((item) => {
            if (item.type === "img") {
              imgFlag = true;
              item.class = refClass;
            }
          });
          this.finish = !data.length;
          if (!this.finish) {
            this.list = data.concat(this.list);
            this.$nextTick((_) => {
              if (ops.message_list_id) {
                this.message_container_warp.scrollTop =
                  this.message_container_warp.scrollHeight - scrollHeight;
              } else {
                this.scrollToSeat(false);
              }

              if (imgFlag && this.$refs[refClass]) {
                this.$refs[refClass].forEach((item) => {
                  imgMap.set(item.$el, item.setImgUrl);
                  this.IO.observe(item.$el);
                });
                this.number++;
              }
            });
          }
        })
        .finally((_) => {
          this.loading = false;
        });
    },

    scrollToSeat(flag) {
      const top = this.message_container_warp.scrollHeight;
      this.message_container_warp.scrollTo({
        top: top,
        behavior: flag ? "smooth" : "instant",
      });
    },
  },
};
</script>

<style lang="less" scoped>
.room {
  height: 500px;
  display: flex;
  flex-direction: column;

  .content_warp {
    overflow: hidden;
  }

  .message_container_warp {
    height: 500px;
    overflow: auto;
  }

  .tools {
    user-select: none;
    padding: 0 8px;
    height: 70px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
    background-color: #fff;
    flex-shrink: 0;
  }

  .entry_box {
    height: 170px;
    box-sizing: border-box;
    padding: 10px 10px 35px;
    position: relative;
    flex-shrink: 0;
  }

  .entry_box_btn {
    position: absolute;
    bottom: 0px;
    right: 0;
  }

  .editor_content {
    height: 100%;
    overflow-y: auto;
    font-size: 15px;
    white-space: pre-wrap;
    word-break: break-word;
    word-wrap: break-word;
  }
  .editor_content[contenteditable]:empty:before {
    content: attr(placeholder);
    color: #464545;
    font-size: 14px;
    font-weight: 400;
  }

  .editor_content[contenteditable]:focus {
    content: none;
  }

  .messageRoom_item {
    display: flex;
    align-items: flex-start;
    padding: 0 100px 0 0;
  }
  .messageRoom_item_image {
    width: 35px;
    height: 35px;
    border-radius: 4px;
    flex-shrink: 0;
    margin: 0 10px 0 0;
  }
  .messageRoom_item_message {
    padding: 6px;
    background-color: #ffffff;
    border-radius: 4px;
    font-size: 16px;
    white-space: pre-line;
    word-break: break-word;
    word-wrap: break-word;
  }
  .messageRoom_right {
    flex-direction: row-reverse;
    padding: 0 0 0 100px;
    .messageRoom_item_image {
      margin: 0 0 0 10px;
    }
    .messageRoom_item_message {
      background-color: #66bfa4;
      color: #ffffff;
    }
  }
  .showPointer {
    display: flex;
    align-items: center;
    flex-direction: column;
  }
}
</style>
